import { Component, Input, OnInit } from '@angular/core';
import { NavParams } from 'ionic-angular';
import { TabService } from '../../../work-station/service/tab.service';
import { UserService } from '../../../../shared/models/services/user.service';
import { TabCardService } from '../../../work-station/service/card-list.service';
import { UserDto } from '../../../../shared/models/dto/user.dto';
import { Tab } from '../../models/tab.modle';
import * as LANG from '../../../../util/constant';

import { API } from "../../../../shared/models/api-path-extension";

@Component({
  selector: 'custom-page',
  templateUrl: 'custom-page.page.html'
})
export class CustomPage implements OnInit {

  @Input() tab: Tab;
  api: API;
  userInfo: UserDto = null;
  constructor(
    public navParams: NavParams,
    public tabCardService: TabCardService,
    public tabService: TabService,
    public userService: UserService
  ) {
    this.tab = this.navParams.data;
    this.api = new API();
    this.userService.getUser().then((user) => this.userInfo = user);
  }

  ngOnInit() {
    this.loadCard();
  }

  loadCard() {
    this.tabService.loadTabs().then((res) => {
      const tabs = res['data'];
      this.tab = tabs.find((tab) => tab.id === this.tab.id);
    });
  }

  addCard() {
    const cardName = prompt(LANG.INPUT_TAB_CARD);
    if (!cardName) {
      return;
    }
    this.tabCardService.addCard({
      name: cardName,
      isAvailable: 1,
      sequence: 1,
      tagId: this.tab.id,
      userId: this.userInfo.id
    }).then((_res) => {
      this.loadCard();
    }, (err) => alert(LANG.HANDLE_ERROR));
  }

  delCard(card) {
    if (confirm(LANG.DEL_TAB_CARD + card.name)) {
      this.tabCardService.delCard(card).then((res) => {
        const cardList = this.tab.tagCardVoList;
        const cardIndex = cardList.findIndex((c) => c.id === card.id);
        this.tab.tagCardVoList.splice(cardIndex, 1);
      }, (err) => alert(LANG.HANDLE_ERROR));
    }
  }
}
